#include <TimerOne.h>
#include <SoftwareSerial.h> 

#define CONTROL A0
#define RELAY 6
#define PULSE_NUMBER 11
#define RATIO 54
#define RADIUS 0.0325
#define PAI 3.1415926
#define SET_TIME 0.005
#define TXD 12
#define RXD 13


double encoder=0;
double encoder_last=0;
double encoder_minus=0;
double carspeed=0;
double caromega=0;
double counttime=0;
//char val;

SoftwareSerial BT(TXD, RXD);

void setup() {
  // put your setup code here, to run once:
  pinMode(CONTROL,INPUT);
  pinMode(2,INPUT_PULLUP);
  pinMode(3,INPUT_PULLUP);
  //pinMode(13,OUTPUT);
  pinMode(RELAY,OUTPUT);
  
  Serial.begin(9600);
  BT.begin(9600);

  attachInterrupt(0, onChange1, RISING);
  Timer1.initialize(5000);
  Timer1.attachInterrupt(TimeChange);
  //digitalWrite(13,HIGH);

}

void onChange1(){
  encoder++;
  //Serial.println("encoder1 ++");
}

void TimeChange(){
  encoder_minus = encoder - encoder_last;
  encoder_last = encoder;
}


void loop() {
  // put your main code here, to run repeatedly:
  caromega = (encoder_minus * 2 * PAI) / (PULSE_NUMBER * RATIO * SET_TIME);
  carspeed = caromega * RADIUS;
  BT.println(carspeed);
  Serial.println(carspeed);

  if(analogRead(CONTROL) <= 500){
    digitalWrite(RELAY,HIGH);
  }else{
    digitalWrite(RELAY,LOW);
  }

  

  
}
